﻿//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Expenses.ViewModels;
using Expenses.ExpenseService;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using Windows.UI.Popups;
using Windows.UI.StartScreen;
using Expenses.Controls;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI;
using Callisto.Controls;

namespace Expenses.Views
{
    public sealed partial class ChargePage : Expenses.Common.LayoutAwarePage
    {
        ChargeViewModel charge = null;
        DataTransferManager dataTransferManager = null;
        string billedAmountTextBoxText = string.Empty;
        string transactionAmountTextBoxText = string.Empty;

        public ChargePage()
        {
            this.InitializeComponent();

            PopulateCategories();
            PopulateOtherCategories();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter == null)
            {
                charge = new ChargeViewModel();
                charge.EmployeeId = App.EmployeeId;
                charge.ExpenseType = Convert.ToInt32(ExpenseItemType.Personal);

                ExpenseDatePicker.Visibility = Visibility.Visible;
                MerchantTextBox.Visibility = Visibility.Visible;
                LocationTextBox.Visibility = Visibility.Visible;
                BilledAmountTextBox.Visibility = Visibility.Visible;
                TransactionAmountTextBox.Visibility = Visibility.Visible;
                DeleteChargeButton.Visibility = Visibility.Collapsed;

                this.DataContext = charge;
                ExpenseTypeTextBlock.Text = "Personal charge";
                PageTitleTextBlock.Text = "New Charge";
            }
            else
            {
                charge = (ChargeViewModel)e.Parameter;
                this.DataContext = charge;
                CategoriesComboBox.SelectedItem =
                    Helpers.GetCategoryName(charge.Category);
                if (CategoriesComboBox.SelectedItem.ToString() == "Other")
                {
                    OtherCategoriesComboBox.SelectedItem =
                        Helpers.GetOtherCategoryName(charge.AccountNumber);
                }
                ExpenseDatePicker.Date = charge.ExpenseDate;
                SnappedExpenseDatePicker.Date = charge.ExpenseDate;

                PageTitleTextBlock.Text = string.Format("{0} on {1:d} for {2:C}",
                    charge.Merchant, charge.ExpenseDate, charge.BilledAmount);

                if (charge.ExpenseType == Convert.ToInt32(ExpenseItemType.Personal))
                {
                    ExpenseDatePicker.Visibility = Visibility.Visible;
                    MerchantTextBox.Visibility = Visibility.Visible;
                    LocationTextBox.Visibility = Visibility.Visible;
                    BilledAmountTextBox.Visibility = Visibility.Visible;
                    TransactionAmountTextBox.Visibility = Visibility.Visible;
                    DeleteChargeButton.Visibility = Visibility.Visible;
                }
                else
                {
                    ExpenseDateTextBlock.Text = charge.ExpenseDate.ToString("d");
                    ExpenseDateTextBlock.Visibility = Visibility.Visible;
                    MerchantTextBlock.Visibility = Visibility.Visible;
                    LocationTextBlock.Visibility = Visibility.Visible;
                    BilledAmountTextBlock.Visibility = Visibility.Visible;
                    TransactionAmountTextBlock.Visibility = Visibility.Visible;
                }

            }
            // Register handler for DataRequested events for sharing
            dataTransferManager = DataTransferManager.GetForCurrentView();
            dataTransferManager.DataRequested += new TypedEventHandler<
                DataTransferManager, DataRequestedEventArgs>(OnDataRequested);

            charge.IsDirty = false;
        }

        private void CategoriesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CategoriesComboBox.SelectedItem == null)
            {
                return;
            }
            string category = CategoriesComboBox.SelectedItem.ToString();
            charge.Category = Helpers.GetCategoryNumber(category);

            if (category == "Other")
            {
                OtherCategoriesComboBox.IsEnabled = true;
            }
            else
            {
                OtherCategoriesComboBox.IsEnabled = false;
            }
            CategoryErrorTextBlock.Visibility = Visibility.Collapsed;
        }

        private void OtherCategoriesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (OtherCategoriesComboBox.SelectedItem == null)
            {
                return;
            }
            string otherCategory = OtherCategoriesComboBox.SelectedItem.ToString();
            charge.AccountNumber = Helpers.GetOtherCategoryNumber(otherCategory);
            OtherCategoryErrorTextBlock.Visibility = Visibility.Collapsed;
        }

        private void SaveChargeButton_Click(object sender, RoutedEventArgs e)
        {
            SaveCharge();
        }

        private async void SaveCharge()
        {
            // Validate the charge
            if (charge.Merchant == string.Empty)
            {
                MerchantErrorTextBlock.Visibility = Visibility.Visible;
                return;
            }
            if (charge.BilledAmount <= 0)
            {
                BilledAmountErrorTextBlock.Visibility = Visibility.Visible;
                return;
            }
            if (charge.TransactionAmount <= 0)
            {
                TransactionAmountErrorTextBlock.Visibility = Visibility.Visible;
                return;
            }
            if (charge.Description == string.Empty)
            {
                DescriptionErrorTextBlock.Visibility = Visibility.Visible;
                return;
            }
            if (charge.Category == 0)
            {
                CategoryErrorTextBlock.Visibility = Visibility.Visible;
                return;
            }
            if (charge.Category == 8 && charge.AccountNumber == 0)
            {
                OtherCategoryErrorTextBlock.Visibility = Visibility.Visible;
                return;
            }

            charge.ExpenseDate = ExpenseDatePicker.Date;

            string result = await charge.SaveCharge(charge);

            if (result.Contains("Success"))
            {
                GoBack();
            }
            else
            {
                var flyout = new Flyout();
                flyout.Content = new TextBlock()
                {
                    Text = result,
                    Foreground = new SolidColorBrush(Colors.Black),
                    Margin = new Thickness(10, 0, 10, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 18
                };
                flyout.Placement = PlacementMode.Top;
                flyout.PlacementTarget = SaveChargeButton;
                flyout.IsOpen = true;
            }
        }

        private async void ShowMessage(string errorMessage)
        {
            var dlg = new Windows.UI.Popups.MessageDialog(errorMessage);
            dlg.Commands.Add(new Windows.UI.Popups.UICommand("OK", null, "OK"));
            await dlg.ShowAsync();
        }

        private async void DeleteChargeButton_Click(object sender, RoutedEventArgs e)
        {
            string result = await charge.DeleteCharge(charge.Id);

            this.Frame.Navigate(typeof(ChargesPage));
        }

        private void BilledAmountTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            BilledAmountTextBox.SelectAll();
        }

        private void BilledAmountTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            billedAmountTextBoxText = BilledAmountTextBox.Text;
            if (BilledAmountTextBox.Text.Substring(0, 1) == "$")
            {
                billedAmountTextBoxText = BilledAmountTextBox.Text.Substring(1);
            }

            if (Convert.ToDecimal(billedAmountTextBoxText) > 0M)
            {
                BilledAmountErrorTextBlock.Visibility = Visibility.Collapsed;
            }

            charge.ReceiptRequired =
                (BilledAmountTextBox.Text != string.Empty &&
                 Convert.ToDecimal(billedAmountTextBoxText) > 75M);
        }

        private void TransactionAmountTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            TransactionAmountTextBox.SelectAll();
        }

        private void TransactionAmountTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            transactionAmountTextBoxText = TransactionAmountTextBox.Text;
            if (TransactionAmountTextBox.Text.Substring(0, 1) == "$")
            {
                transactionAmountTextBoxText = TransactionAmountTextBox.Text.Substring(1);
            }

            if (Convert.ToDecimal(transactionAmountTextBoxText) > 0M)
            {
                TransactionAmountErrorTextBlock.Visibility = Visibility.Collapsed;
            }
        }

        private void MerchantTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (MerchantTextBox.Text != string.Empty)
            {
                MerchantErrorTextBlock.Visibility = Visibility.Collapsed;
            }
        }

        private void DescriptionTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (DescriptionTextBox.Text != string.Empty)
            {
                DescriptionErrorTextBlock.Visibility = Visibility.Collapsed;
            }
        }

        private void ExpenseDatePicker_LostFocus(object sender, RoutedEventArgs e)
        {
            if (ExpenseDatePicker.Date != SnappedExpenseDatePicker.Date)
            {
                SnappedExpenseDatePicker.Date = ExpenseDatePicker.Date;
            }
        }

        private void SnappedExpenseDatePicker_LostFocus(object sender, RoutedEventArgs e)
        {
            if (ExpenseDatePicker.Date != SnappedExpenseDatePicker.Date)
            {
                ExpenseDatePicker.Date = SnappedExpenseDatePicker.Date;
            }
        }

        private async void BackButton_Click(object sender, RoutedEventArgs e)
        {
            if (charge.IsDirty == true)
            {
                var messageDialog = new MessageDialog(
                    "Do you want to save your changes?", "You made changes");
                messageDialog.Commands.Add(new UICommand("Save", (command) =>
                {
                    SaveCharge();
                }));
                messageDialog.Commands.Add(new UICommand("Don't save", (command) =>
                {
                }));
                messageDialog.DefaultCommandIndex = 1;
                await messageDialog.ShowAsync();
            }
            GoBack();
        }

        private void GoBack()
        {
            switch (App.LastPage)
            {
                case "ChargesPage":
                    this.Frame.Navigate(typeof(ChargesPage));
                    break;
                case "ExpenseReportPage":
                    this.Frame.Navigate(typeof(ExpenseReportPage));
                    break;
                default:
                    this.Frame.Navigate(typeof(MainPage));
                    break;
            }
        }

        void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var request = args.Request;
            request.FailWithDisplayText("This page does not support sharing.");
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            dataTransferManager.DataRequested -= new TypedEventHandler<
                DataTransferManager, DataRequestedEventArgs>(OnDataRequested);
            App.LastPage = "ChargePage";
        }

        public static Rect GetElementRect(FrameworkElement element)
        {
            GeneralTransform buttonTransform = element.TransformToVisual(null);
            Point point = buttonTransform.TransformPoint(new Point());
            return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
        }

        private void PopulateCategories()
        {
            CategoriesComboBox.Items.Clear();
            CategoriesComboBox.Items.Add("Airfare");
            CategoriesComboBox.Items.Add("Car Rental");
            CategoriesComboBox.Items.Add("Conference/Seminar");
            CategoriesComboBox.Items.Add("Entertainment");
            CategoriesComboBox.Items.Add("Gifts");
            CategoriesComboBox.Items.Add("Hotel");
            CategoriesComboBox.Items.Add("Mileage");
            CategoriesComboBox.Items.Add("Other");
            CategoriesComboBox.Items.Add("Other Travel & Lodging");
            CategoriesComboBox.Items.Add("T&E Meals");
        }

        private void PopulateOtherCategories()
        {
            OtherCategoriesComboBox.Items.Clear();
            OtherCategoriesComboBox.Items.Add("Admin Services");
            OtherCategoriesComboBox.Items.Add("Cell Phone");
            OtherCategoriesComboBox.Items.Add("Computer Services");
            OtherCategoriesComboBox.Items.Add("Computer Supplies & Equipment");
            OtherCategoriesComboBox.Items.Add("Employee Morale");
            OtherCategoriesComboBox.Items.Add("General Supplies");
            OtherCategoriesComboBox.Items.Add("Home Broadband");
            OtherCategoriesComboBox.Items.Add("Phone/Fax");
            OtherCategoriesComboBox.Items.Add("Postage");
            OtherCategoriesComboBox.Items.Add("Recruit Meals");
            OtherCategoriesComboBox.Items.Add("Recruit Travel");
            OtherCategoriesComboBox.Items.Add("Recruit Other");
            OtherCategoriesComboBox.Items.Add("Reference Material");
            OtherCategoriesComboBox.Items.Add("Training");
            OtherCategoriesComboBox.Items.Add("Travel Broadband");
        }

    }
}
